package com.yya.ratelimiter.config;

import com.sun.deploy.util.SystemUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Autor: yuanyongan
 * @Description: 线程池配置
 * @Date 2023/1/12 10:43
 */
@Configuration
public class ExecutorConfig {
    /**
     * 核心线程数，根据机器CPU数目修改
     */
    private static final int corePoolSize = 8;

    /**
     * 阻塞队列容量
     */
    private static final int queueCapacity = 1 << 10;

    /**
     * 最大线程数
     * 1、当线程数>=corePoolSize时，任务会放入阻塞队列
     * 2、当阻塞队列满了之后。会创建新线程来处理任务
     * 3、当线程总数=maxPoolSize时， 线程池会执行拒绝策略，默认策略为拒绝处理任务，并抛出异常
     */
    private static final int maxPoolSize = 16;

    /**
     * 线程被回收前的空闲时间
     * 当线程空闲时间达到keepAliveSeconds时，线程会退出，直到线程数量=corePoolSize
     * 如果如果allowCoreThreadTimeout=true，则会直到线程数量=0
     */
    private static final int keepAliveSeconds = 60;

    /**
     * 线程池中线程前缀名称
     */
    private static final String executorName = "Async-Executor-";

    /**
     * 拒绝策略
     * AbortPolicy：拒绝执行，并抛出异常（一般的默认策略）
     * DiscardPolicy：直接抛弃，拒绝执行
     * DiscardOldestPolicy：将阻塞队列中最早加入的任务抛弃，然后将当前任务加入
     * CallerRunsPolicy：直接在当前线程执行任务，会出现阻塞排队的情况
     */
    private static final RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();

    /**
     * 线程池配置
     * @return
     */
    @Bean(name = "executor")
    public Executor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(executorName);
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        return executor;
    }
}
